﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using Conducido.WcfMessageLogger.Services.Behaviors.Entities.Config;
using Conducido.WcfMessageLogger.Services.Behaviors.Logger;

namespace Conducido.WcfMessageLogger.Services.Behaviors
{   
    /// <summary>
    /// <see cref="IDispatchMessageInspector"/> implementation which can be called from a behavior.
    /// 
    /// </summary>
    public class ServiceCorrelation : IDispatchMessageInspector
    {
        private CorrelationConfiguration _correlationConfiguration;

        /// <summary>
        /// We need it to configurate it
        /// </summary>
        /// <param name="correlationConfiguration"></param>
        public ServiceCorrelation(CorrelationConfiguration correlationConfiguration)
        {
            _correlationConfiguration = correlationConfiguration;
        }

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (_correlationConfiguration != null && _correlationConfiguration.ShouldCorrelate)
            {
                LogOperator messageManager = null;
                try
                {
                    if (request != null && !request.IsEmpty)
                    {
                        messageManager = new LogOperator(request, _correlationConfiguration);
                        messageManager.AddCorrelationToContext();
                        request = messageManager.CopyMessage();
                    }

                }
                catch (Exception exception)
                {
                    if (messageManager != null)
                    {
                        request = messageManager.CopyMessage();
                    }
                    Debug.WriteLine(exception.Message);
                }
            }
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            
        }
    }
}
